package dating.controller;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dating.model.User;
import dating.service.RegisterServiceLocal;

public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@EJB
	private RegisterServiceLocal registerService;

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		DateFormat df = null;
		Date date = null;
		try {
		    df = new SimpleDateFormat("dd-MM-yyyy");
		    String dateOfBirth = request.getParameter("date_of_birth");
		    date = df.parse(dateOfBirth);
		} catch(Exception e){
			e.printStackTrace();
		}
		String astralSign = request.getParameter("astral_sign");
		String sex = request.getParameter("sex");
		String city = request.getParameter("city");
		String description = request.getParameter("description");

		System.out.println("trying to register" + username);
		User user =new User(name, username, password,
				date, astralSign,
				sex, city, description);

		if (registerService.register(user)) {
			request.getSession().setAttribute("user_id", user.getId());
			response.sendRedirect("profile?id=" + user.getId());
		} else {
			response.sendRedirect("login");
		}
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	public String getServletInfo() {
		return "Short description";
	}
}
